package com.cyzy.homework.service.impl;

import com.cyzy.homework.entity.Message;
import com.cyzy.homework.repository.MessageRepository;
import com.cyzy.homework.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 消息服务实现类
 */
@Slf4j
@Service
public class MessageServiceImpl implements MessageService {
    
    @Autowired
    private MessageRepository messageRepository;
    
    @Override
    @Transactional
    public Message sendMessage(String fromUserId, String fromUser, String toUserId, 
                              String title, String content, String type, String level, String extraData) {
        Message message = new Message();
        message.setMessageId(generateMessageId());
        message.setFromUserId(fromUserId);
        message.setFromUser(fromUser);
        message.setToUserId(toUserId);
        message.setTitle(title);
        message.setContent(content);
        message.setType(type != null ? type : "text");
        message.setLevel(level != null ? level : "info");
        message.setIsRead(0);
        message.setStatus(0);
        message.setExtraData(extraData);
        
        Timestamp now = Timestamp.valueOf(LocalDateTime.now());
        message.setSendTime(now);
        message.setCreateTime(now);
        message.setUpdateTime(now);
        
        Message savedMessage = messageRepository.save(message);
        log.info("消息发送成功: {} -> {}, 内容: {}", fromUser, toUserId, content);
        return savedMessage;
    }
    
    @Override
    public Message sendSystemMessage(String toUserId, String title, String content, String level) {
        return sendMessage("system", "系统消息", toUserId, title, content, "system", level, null);
    }
    
    @Override
    public Message sendWelcomeMessage(String toUserId, String userName, String userRole) {
        String title = "欢迎登录";
        String content = generateWelcomeContent(userName, userRole);
        return sendSystemMessage(toUserId, title, content, "info");
    }
    
    @Override
    @Transactional
    public List<Message> sendBatchMessages(String fromUserId, String fromUser, List<String> toUserIds,
                                          String title, String content, String type, String level, String extraData) {
        List<Message> messages = new ArrayList<>();
        for (String toUserId : toUserIds) {
            Message message = sendMessage(fromUserId, fromUser, toUserId, title, content, type, level, extraData);
            messages.add(message);
        }
        return messages;
    }
    
    @Override
    public Page<Message> getUserMessages(String userId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "sendTime"));
        return messageRepository.findByToUserIdAndStatusOrderBySendTimeDesc(userId, 0, pageable);
    }
    
    @Override
    public Page<Message> getUserMessagesByType(String userId, String type, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "sendTime"));
        return messageRepository.findByToUserIdAndTypeAndStatusOrderBySendTimeDesc(userId, type, 0, pageable);
    }
    
    @Override
    public Page<Message> getUserUnreadMessages(String userId, int page, int size) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "sendTime"));
        return messageRepository.findByToUserIdAndIsReadAndStatusOrderBySendTimeDesc(userId, 0, 0, pageable);
    }
    
    @Override
    public List<Message> getRecentMessages(String userId, int limit) {
        Pageable pageable = PageRequest.of(0, limit);
        return messageRepository.findRecentMessages(userId, pageable);
    }
    
    @Override
    public Message getMessageById(String messageId, String userId) {
        return messageRepository.findByMessageId(messageId)
                .filter(message -> message.getToUserId().equals(userId) && message.getStatus() == 0)
                .orElse(null);
    }
    
    @Override
    @Transactional
    public boolean markAsRead(String messageId, String userId) {
        Timestamp now = Timestamp.valueOf(LocalDateTime.now());
        int result = messageRepository.markAsRead(messageId, userId, now, now);
        return result > 0;
    }
    
    @Override
    @Transactional
    public int markAllAsRead(String userId) {
        Timestamp now = Timestamp.valueOf(LocalDateTime.now());
        return messageRepository.markAllAsRead(userId, now, now);
    }
    
    @Override
    @Transactional
    public boolean deleteMessage(String messageId, String userId) {
        Timestamp now = Timestamp.valueOf(LocalDateTime.now());
        int result = messageRepository.deleteMessage(messageId, userId, now);
        return result > 0;
    }
    
    @Override
    public long getUnreadCount(String userId) {
        return messageRepository.countByToUserIdAndIsReadAndStatus(userId, 0, 0);
    }
    
    @Override
    public long getUnreadCountByType(String userId, String type) {
        return messageRepository.countByToUserIdAndTypeAndIsReadAndStatus(userId, type, 0, 0);
    }
    
    @Override
    @Transactional
    public int cleanupExpiredMessages(int daysToKeep) {
        LocalDateTime expireTime = LocalDateTime.now().minusDays(daysToKeep);
        Timestamp expireTimestamp = Timestamp.valueOf(expireTime);
        return messageRepository.cleanupExpiredMessages(expireTimestamp);
    }
    
    /**
     * 生成消息ID
     */
    private String generateMessageId() {
        return "msg_" + UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }
    
    /**
     * 生成欢迎消息内容
     */
    private String generateWelcomeContent(String userName, String userRole) {
        int hour = LocalDateTime.now().getHour();
        String timeGreeting;
        
        if (hour >= 5 && hour < 12) {
            timeGreeting = "早上好";
        } else if (hour >= 12 && hour < 14) {
            timeGreeting = "中午好";
        } else if (hour >= 14 && hour < 18) {
            timeGreeting = "下午好";
        } else if (hour >= 18 && hour < 22) {
            timeGreeting = "晚上好";
        } else {
            timeGreeting = "夜深了";
        }
        
        String roleInfo = "1".equals(userRole) || "admin".equals(userRole) ? 
            "，祝您教学工作顺利！" : "，祝您学习愉快！";
        
        return String.format("%s，%s！欢迎登录EduLiveLink智能直播教育平台%s", 
                           timeGreeting, userName, roleInfo);
    }
}





















